package com.smzh.common;

import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.annotations.FromAnnotationsRuleModule;
import org.apache.commons.digester3.binder.RulesModule;

public class AnnotatedPojoUtil {

	static {

	}

	public AnnotatedPojoUtil() {

	}

	// 将xml转换为Bean
	/**
	 * 
	 * @param clazz
	 *            类class
	 * @param xmlPath
	 *            xml路径
	 * @return 返回对象
	 * @throws Exception
	 */
	public static Object xmlParseToObject(final Class<?> clazz, String xmlPath) throws Exception {
		// final Class<?> clazz = expected.getClass();
		// String resource = clazz.getSimpleName() + ".xml";
		InputStream input = clazz.getResourceAsStream(xmlPath);

		Collection<RulesModule> modules = new ArrayList<RulesModule>();
		modules.add(new FromAnnotationsRuleModule() {

			@Override
			protected void configureRules() {
				bindRulesFrom(clazz);
			}

		});

		Digester digester = newLoader(modules).newDigester();
		Object actual = digester.parse(input);

		if (input != null) {
			input.close();
		}
		return actual;
	}
}
